package com.jrwd.recycletest.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.format.DateFormat;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by ${templefck} on 2018/8/7.
 */
public class PhotoUtils {
    /**
     * 请求裁剪头像
     */
    public static final int PiC_FROM_CROP = 100;
    /**
     * 请求相机
     */
    public static final int TAKE_CAMERA_OK = 1;
    /**
     * 请求相册
     */
    public static final int TAKE_PHOTO_OK = 2;
    public static File file;

    /**
     * 裁剪图片
     * @param activity
     * @param uri
     * @param aspectX
     * @param aspectY
     * @param outputX
     * @param outputY
     */
    public static void zoomPhoto(Activity activity, Uri uri, int aspectX, int aspectY,
                                 int outputX, int outputY){
        String name   = (String) DateFormat.format("yyyyMMddHHmmss", System.currentTimeMillis()) + ".jpg";
        file = new File(SDCardUtils.getSDPath(), name);
        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);

        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);


        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, PiC_FROM_CROP);

    }

    /**
     * 裁剪图片
     * @param fragment
     * @param uri
     * @param aspectX
     * @param aspectY
     * @param outputX
     * @param outputY
     */
    public static void zoomPhoto(Fragment fragment, Uri uri, int aspectX, int aspectY,
                                 int outputX, int outputY){
        String name   = (String) DateFormat.format("yyyyMMddHHmmss", System.currentTimeMillis()) + ".jpg";
        file = new File(SDCardUtils.getSDPath(), name);
        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);

        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);


        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        fragment.startActivityForResult(intent, PiC_FROM_CROP);

    }


    /**
     * 调用系统相机拍照
     * @param activity
     * @param mFile
     */
    public static void photograph(Activity activity, File mFile) {

        Context context = activity.getApplicationContext();
        Intent intent  = null;
        Uri pictureUri;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            pictureUri = FileProvider.getUriForFile(context, context.getPackageName()+".fileProvider", mFile);
        }else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(mFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        activity.startActivityForResult(intent, TAKE_CAMERA_OK);

    }

    /**
     * 调用系统相机拍照
     * @param activity
     * @param mFile
     */
    public static void photo(Fragment activity, File mFile) {
        String name = (String) DateFormat.format("yyyyMMddHHmmss", System.currentTimeMillis()) + ".jpg";
        Context context = activity.getContext();
        //        new File(SDCardUtils.getSDCardPath(), fileName));
        mFile = new File(SDCardUtils.getSDPath(),name);
        Intent intent = null;
        Uri pictureUri;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            pictureUri = FileProvider.getUriForFile(context, context.getPackageName()+".fileProvider", mFile);
        }else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(mFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        activity.startActivityForResult(intent, TAKE_CAMERA_OK);

        //        context.startActivity(intent);
        //        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
        //        activity.startActivityForResult(intent, TAKE_CAMERA_OK);
    }
    /**
     * 调用系统相机拍照
     * @param fragment
     * @param mFile
     */
    public static void photograph(Fragment fragment, File mFile) {

        Context context = fragment.getActivity().getApplicationContext();
        Intent intent = null;
        Uri pictureUri;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            pictureUri = FileProvider.getUriForFile(context, context.getPackageName()+".fileProvider", mFile);
            //com.jrweid.ydxyk.fileProvider
        }else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(mFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        fragment.startActivityForResult(intent, TAKE_CAMERA_OK);
    }

    /**
     * 打开图库选择相片
     * @param activity
     */
    public static void openPhotoStorage(Activity activity) {
        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activity.startActivityForResult(i, TAKE_PHOTO_OK);
    }

    /**
     * 打开图库选择相片
     * @param fragment
     */
    public static void openPhotoStorage(Fragment fragment) {
        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        fragment.startActivityForResult(i, TAKE_PHOTO_OK);
    }

    /**
     * 根据uri转化为path
     * @param context
     * @param uri
     * @return
     */
    public static String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals(scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query(uri, new String[] {MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 压缩图片
     * @param imagePath
     */
    public static Bitmap compress(String imagePath){
        // 设置参数
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 只获取图片的大小信息，而不是将整张图片载入在内存中，避免内存溢出
        BitmapFactory.decodeFile(imagePath, options);
        int height = options.outHeight;
        int width= options.outWidth;
        int inSampleSize = 1; // 默认像素压缩比例，压缩为原图的1/2
        int minLen = Math.min(height, width); // 原图的最小边长
        if(minLen > 100) { // 如果原始图像的最小边长大于100dp（此处单位我认为是dp，而非px）
            float ratio = (float)minLen / 100.0f; // 计算像素压缩比例
            inSampleSize = (int)ratio;
        }
        options.inJustDecodeBounds = false; // 计算好压缩比例后，这次可以去加载原图了
        options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options); // 解码文件
        //        L.e("size: " + bitmap.getByteCount() + " width: " + bitmap.getWidth() + " heigth:"
        //                + bitmap.getHeight());
        return bitmap;
    }

    /**
     * 读取uri所在的图片
     * @param uri
     *         图片对应的Uri
     * @param mContext
     *         上下文对象
     * @return 获取图像的Bitmap
     */
    public static Bitmap getBitmapFromUri(Uri uri, Context mContext) {
        try {
            Bitmap bitmap = MediaStore.Images.Media.
                                                           getBitmap(mContext.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 质量压缩法：
    public static Bitmap compressImage(String imagePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inPurgeable = true; // 计算好压缩比例后，这次可以去加载原图了
        options.inSampleSize = 2; // 设置为刚才计算的压缩比例
        BitmapFactory.decodeFile(imagePath, options);
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options); // 解码文件
        ByteArrayOutputStream baos   = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int option = 100;
        while ((baos.toByteArray().length / 1024 > 100)&&(option>0)) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            option -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, option, baos);//这里压缩options%，把压缩后的数据存放到baos中

        }
        //压缩好后写入文件中
        return bitmap;

    }

    /**
     * 处理旋转后的图片
     * @param originpath 原图路径
     * @param context 上下文
     * @return 返回修复完毕后的图片路径
     */
    public static File amendRotatePhoto(String originpath, Context context) {

        // 取得图片旋转角度
        int angle = readPictureDegree(originpath);

        // 把原图压缩后得到Bitmap对象
        //        Bitmap bmp = compress(originpath);
        Bitmap bmp1 = BitmapFactory.decodeFile(originpath);

        // 修复图片被旋转的角度
        Bitmap bitmap = rotaingImageView(angle, bmp1);

        // 保存修复后的图片并返回保存后的图片文件

        return saveBitmapFile(bitmap);
    }


    public static File saveBitmapFile(Bitmap bitmap){
        String name = (String) DateFormat.format("yyyyMMddHHmmss", System.currentTimeMillis()) + ".jpg";
        File file=new File(SDCardUtils.getSDPath(),name);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    /**
     * 把原图按1/10的比例压缩
     *
     * @param path 原图的路径
     * @return 压缩后的图片
     */
    public static Bitmap getCompressPhoto(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 1;  // 图片的大小设置为原来的十分之一
        Bitmap bmp = BitmapFactory.decodeFile(path, options);
        options = null;
        return bmp;
    }
    /**
     * 读取照片旋转角度
     *
     * @param path 照片路径
     * @return 角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int           orientation   = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    /**
     * 旋转图片
     * @param angle 被旋转角度
     * @param bitmap 图片对象
     * @return 旋转后的图片
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Bitmap returnBm = null;
        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        try {
            if (bitmap==null){
                returnBm = bitmap;
            }else {
                // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
                returnBm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            }
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bitmap;
        }
        if (bitmap != returnBm) {
            bitmap.recycle();
        }
        return returnBm;
    }
}
